package com.heima.article.service.impl;

import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApHotArticles;
import com.heima.article.mapper.ApHotArticlesMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApHotArticlesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 热文章表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class ApHotArticlesServiceImpl extends ServiceImpl<ApHotArticlesMapper, ApHotArticles> implements ApHotArticlesService {

    static final String PREFIX = "leadnews:hotArticles";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApArticleService articleService;

    @Override
    public void calcArticleScore() {
        // 1 查询最近7天发布的文章, 请改成分页，可以使用分片任务
        List<ApArticle> articleList = articleService.findLatestArticlesIn(7);
        // 2 计算文章的热度值
        if(CollectionUtils.isEmpty(articleList)){
            log.warn("7天内一个文章也查不到");
            return;
        }
        for(ApArticle article : articleList){
            double score = calcArticleScore(article);
            // 3 把热度值写入到redis的zset
            redisTemplate.boundZSetOps(PREFIX).add(""+article.getId(), score);
            // 当article上下架的时候，redis中需要同步做上下架，接收消息，同步上下架就可以 TODO
            redisTemplate.boundValueOps(PREFIX+":"+article.getId()).set(JsonUtils.toString(article));
        }
    }

    private double calcArticleScore(ApArticle article){
        double score =  0;
        Long views = article.getViews();
        Long likes = article.getLikes();
        Long comments = article.getComments();
        Long collection = article.getCollection();
        score += views;
        score += 3*likes;
        score += 5*comments;
        score += 8*collection;
        return score;
    }

}
